// import SearchBar from '@/components/SearchBar';
import type { DetailResult, WeiXinUser } from '@/pages/types/type';
import { getRequestInit, urlPrefix } from '@/utils/http';
import {
  Avatar,
  Form,
  Picker,
  Popup,
  SearchBar,
  Selector,
  SelectorOption,
  Space,
} from 'antd-mobile';
import { NamePath } from 'antd-mobile/es/components/form';
import type {
  PickerActions,
  PickerColumn,
  PickerColumnItem,
} from 'antd-mobile/es/components/picker';
import React, { FC, RefObject, useEffect, useMemo, useState } from 'react';

// const WeiXinUserSelect = ({ value, onChange, popupVisible, setPopupVisible }: { value?: undefined | WeiXinUser, popupVisible: boolean, onChange?: (val: undefined | WeiXinUser) => void | undefined, setPopupVisible: (x: boolean) => void }) => {
//     const [weiXinUsers, setWeiXinUsers] = useState<WeiXinUser[]>([])
//     const [searchText, setSearchText] = useState<string | undefined>('')
//     const [loading, setLoading] = useState<boolean>(true);
//     const [loadFail, setLoadFail] = useState<string | undefined>(undefined);
//     const [loadSuccess, setLoadSuccess] = useState<string | undefined>(undefined);

//     const [searching, setSearching] = useState<boolean | undefined>(false);
//     const searchRef = useRef<SearchBarRef>(null);

//     function load() {
//         setLoading(true);
//         setLoadFail(undefined);
//         setLoadSuccess(undefined);
//         const headers = { 'Authorization': `Bearer ${localStorage.getItem(ACCESSTOKEN)}`, "Content-Type": "application/json" }
//         const requestInit: RequestInit = { mode: 'cors', cache: 'no-cache', credentials: 'same-origin', redirect: 'follow', method: 'get', headers };
//         let response: Promise<Response> = fetch(`${urlPrefix}/api/wei-xin-user-search/all`, requestInit)
//         response.then((rsp: Response) => {
//             console.log(rsp);
//             if (rsp.ok) {

//                 rsp.json().then(({ data, code, msg }: PageResult<WeiXinUser>) => {
//                     if (code === 0) {
//                         setWeiXinUsers(code === 0 && data ? data : [])
//                         setLoadSuccess(msg);
//                     } else {
//                         setLoadFail(msg);
//                     }
//                 }).catch(reason => {
//                     setLoadFail(reason);
//                 })
//             }
//         }).catch((reason: any) => {
//             console.error(reason);
//             setLoadFail(`发生错误：${reason}`)
//         }).finally(() => {
//             setLoading(false);
//         })
//     }
//     useEffect(load, []);

//     function search(name: string) {
//         setSearching(true);
//         const nativeElement = searchRef.current?.nativeElement;
//         const attr = 'disabled';
//         nativeElement?.setAttribute(attr, 'true');
//         request('/api/wei-xin-user-search', {
//             headers: { 'Authorization': `Bearer ${localStorage.getItem(ACCESSTOKEN)}` }, method: 'post', data: { name }
//         }
//         ).then(({ data, code, msg }: PageResult<WeiXinUser>) => {
//             setWeiXinUsers(code === 0 && data ? data : [])
//             if (code !== 0) {
//                 console.error(msg);
//             }
//             nativeElement?.removeAttribute(attr);
//             setSearching(false);
//         })
//     }

//     return (
//         <React.Fragment>
//             {value ? <Space wrap> <Avatar src={value.thumbAvatar} style={{ '--size': '32px' }} /> {value.name}</Space> : '请选择用户'}
//             <Popup
//                 visible={popupVisible}
//                 onMaskClick={() => { setPopupVisible(false) }}
//                 destroyOnClose
//                 bodyStyle={{ height: '50vh' }}
//             >
//                 <div style={{ marginTop: "8px" }} className={styles.searchBarContainer}>
//                     <SearchBar placeholder='输入员工名称搜索' ref={searchRef}
//                         value={searchText}
//                         onChange={v => { setSearchText(v) }}
//                         onSearch={search}
//                     />
//                 </div>
//                 {searching || loading && <DotLoading />}
//                 <div className={styles.checkListContainer}>
//                     <CheckList
//                         className={styles.myCheckList}
//                         defaultValue={value ? [value.userid] : []}
//                         onChange={ids => {
//                             onChange?.(weiXinUsers.filter(w => w.userid === ids[0])[0])
//                             setPopupVisible(false)
//                         }}
//                     >{weiXinUsers.map(({ userid, name, thumbAvatar }) => (
//                         <CheckList.Item key={userid} value={userid}
//                             prefix={<Avatar src={thumbAvatar} style={{ '--size': '32px' }} />}
//                         >
//                             {name}
//                         </CheckList.Item>
//                     ))}
//                     </CheckList>
//                 </div>
//             </Popup>
//         </React.Fragment>
//     )
// }


const WeiXinUserPicker: FC<{
  name: NamePath;
  required: boolean;
  label: string;
  range?: 'all' | 'employed';
}> = ({ required, label, name, range = 'employed' }) => {
  const [pickerVisible, setPickerVisible] = useState(false);
  const [loading, setLoading] = useState<boolean>(true);
  const [loadFail, setLoadFail] = useState<string | undefined>(undefined);
  const [loadSuccess, setLoadSuccess] = useState<string | undefined>(undefined);
  const [weiXinUsers, setWeiXinUsers] = useState<WeiXinUser[]>([]);
  const [searchText, setSearchText] = useState<string>('');

  const filteredItems = useMemo(() => {
    console.log('searchText=', searchText);
    if (searchText) {
      return weiXinUsers.filter((item) => item.name.includes(searchText));
    } else {
      return weiXinUsers;
    }
  }, [weiXinUsers, searchText]);

  function load() {
    setLoading(true);
    setLoadFail(undefined);
    setLoadSuccess(undefined);
    let response: Promise<Response> = fetch(
      `${urlPrefix}/api/rayplatform/wei-xin-user/${range}`,
      getRequestInit(),
    );
    response
      .then((rsp: Response) => {
        console.log(rsp);
        if (rsp.ok) {
          rsp
            .json()
            .then(async ({ data, code, msg }: DetailResult<WeiXinUser[]>) => {
              if (code === 0) {
                setWeiXinUsers(data!);
                setLoadSuccess(msg);
              } else {
                setLoadFail(msg);
              }
            })
            .catch((reason) => {
              setLoadFail(reason);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFail(`发生错误：${reason}`);
      })
      .finally(() => {
        setLoading(false);
      });
  }
  useEffect(load, []);

  return (
    <Form.Item
      // noStyle
      required={required}
      label={label}
      shouldUpdate={(prevValues, curValues) =>
        prevValues[`${name}`] !== curValues[`${name}`]
      }
      arrow
      onClick={() => {
        setPickerVisible(true);
      }}
    >
      {({ getFieldValue, setFieldsValue }) => {
        return (
          <React.Fragment>
            <Popup
              style={{ zIndex: 1001 }}
              forceRender
              visible={pickerVisible}
              bodyStyle={{ height: '70vh', overflowY: 'scroll' }}
              onMaskClick={() => {
                setPickerVisible(false);
              }}
            >
              <div
                style={{
                  padding: '12px',
                  borderBottom: 'solid 1px var(--adm-color-border)',
                }}
              >
                <SearchBar
                  placeholder="输入用户名过滤"
                  value={searchText}
                  onChange={(v: string) => {
                    setSearchText(v);
                  }}
                />
              </div>

              <Form.Item name={name} noStyle required={required}>
                <Selector
                  columns={3}
                  onChange={(arr, extend) => {
                    console.log(arr, extend.items);
                    setPickerVisible(false);
                  }}
                  options={filteredItems.map(({ name, userid  }) => ({
                    label: name,
                    value: userid
                  }))}
                />
              </Form.Item>
            </Popup>
            <Form.Subscribe to={[name]}>
              {(ot) =>
                ot[name] && ot[name].length > 0 ? (
                  <Space wrap>
                    <Avatar
                      style={{ '--size': '24px' }}
                      src={
                        weiXinUsers.filter((x) => x.userid === ot[name][0])[0]
                          ?.thumbAvatar
                      }
                    />
                    {
                      weiXinUsers.filter((x) => x.userid === ot[name][0])[0]
                        ?.name
                    }
                  </Space>
                ) : (
                  <></>
                )
              }
            </Form.Subscribe>
          </React.Fragment>
        );
      }}
    </Form.Item>
  );
};

const LeadersPopup: FC<{
  url: string;
  visable: boolean;
  setVisable: (x: boolean) => void;
  setSelectLeaders: React.Dispatch<
    React.SetStateAction<SelectorOption<string>[]>
  >;
}> = ({ url, visable, setVisable, setSelectLeaders }) => {
  const [xLeaders, setXLeaders] = useState<WeiXinUser[]>([]);
  const [searchText, setSearchText] = useState<string>('');

  const filteredItems = useMemo(() => {
    console.log('searchText=', searchText);
    if (searchText) {
      return xLeaders.filter((item) => item.name.includes(searchText));
    } else {
      return xLeaders;
    }
  }, [xLeaders, searchText]);

  useEffect(() => {
    fetch(`${urlPrefix}${url}`, getRequestInit())
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({ data, code, msg }: DetailResult<WeiXinUser[]>) => {
              console.log('msg=', msg);
              if (code === 0) {
                setXLeaders(data!);
              } else {
              }
            })
            .catch((reason) => {
              console.log(reason);
            })
            .finally(() => {
              console.log(`${url} inner finally!`);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
      })
      .finally(() => {
        console.log(`${url} outter finally!`);
      });
  }, []);

  return (
    <Popup
      visible={visable}
      onMaskClick={() => {
        setVisable(false);
      }}
      onClose={() => {
        setVisable(false);
      }}
      position="bottom"
      bodyStyle={{ height: '60vh', overflowY: 'scroll' }}
    >
      <div
        style={{
          padding: '12px',
          borderBottom: 'solid 1px var(--adm-color-border)',
        }}
      >
        <SearchBar
          placeholder="输入用户名过滤选项"
          value={searchText}
          onChange={(v: string) => {
            setSearchText(v);
          }}
        />
      </div>

      <div style={{ padding: 20, overflowY: 'scroll' }}>
        <Selector
          columns={3}
          options={filteredItems.map((x) => ({
            value: x.userid,
            label: x.name,
          }))}
          onChange={(
            value: string[],
            extend: { items: SelectorOption<string>[] },
          ) => {
            setSelectLeaders(extend.items);
          }}
          multiple
        />
      </div>
    </Popup>
  );
};

export { LeadersPopup, WeiXinUserPicker };
